package com.jiubanqingchen.future.org.business.login;


import com.jfinal.aop.Aop;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jiubanqingchen.future.common.enums.CacheName;
import com.jiubanqingchen.future.common.enums.SystemStatus;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.admin.BaseController;
import com.jiubanqingchen.future.org.authority.user.UserAuthorityService;
import com.jiubanqingchen.future.org.tool.jwt.JwtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Light_Dust
 * @ClassName: LoginController
 * @Description: (系统用户登录)
 * @date 2019年7月4日 下午1:42:50
 */
public class LoginController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Inject
    LoginService loginService;

    /**
     * @param
     * @return void    返回类型
     * @throws
     * @Title: index
     * @Description: (系统用户登录)
     * @author Light_Dust
     * @date 2019年7月4日 下午1:43:14
     */
    @Clear
    public void index() throws Exception {
        //暂时去掉验证码登录
//		if(!validateCaptcha("captcha")){
//			renderResult(SystemStatus.CAPTCHA_ERROR);
//			return ;
//		}
        User user = loginService.login(getRawDataForObject(User.class));
        if (user != null) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        loginService.handleLoginInfo(getRequest(), user);
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }
            }.start();
            CacheKit.put(CacheName.USER_LIST.getValue(), user.getUserId(), user);
            renderResult(SystemStatus.LOGIN_SUCCESS, JwtService.createToken(user));
        } else {
            renderResult(SystemStatus.LOGIN_ERROR);
        }
    }

    /**
     * @param
     * @return void    返回类型
     * @throws
     * @Title: logout
     * @Description: (退出当前登录用户)
     * @author Light_Dust
     * @date 2019年7月4日 下午1:43:30
     */
    @Clear
    public void logout() {
        UserAuthorityService userAuthorityService = Aop.get(UserAuthorityService.class);
        userAuthorityService.removeAuthorityCache(getCurrentUser().getUserId());
        renderResult(true);
    }

}
